<template>
  <div>
    <div style="margin-bottom: 20px">
      <el-button type="primary" @click="templateAdd()"><i class="el-icon-plus"></i>普通套餐</el-button>
      <el-button type="primary" @click="handleClickSetSort">排序</el-button>
    </div>
    <el-form :model="searchInfo" :inline="true" label-width="70px">
      <div>
      <el-form-item label="分公司">
        <el-input v-model="this.branchName" disabled style="width:150px"></el-input>
      </el-form-item>
      <!-- <el-form-item label="所属部门">
        <el-input v-model="this.deptName" disabled style="width:150px"></el-input>
      </el-form-item> -->
      <el-form-item label="客资类型">
        <el-select v-model="searchInfo.limit_user_type" clearable placeholder="客资类型" style="width:150px" :loading="customerTypeLoading">
          <!-- <el-option value="1" label="普通超市"></el-option> -->
          <el-option v-for="(item, index) in customerTypeList"
          :key="index"
          :label="item.name"
          :value="item.id.toString()"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品类型">
        <el-select v-model="searchInfo.product_type" clearable placeholder="选择商品类型" style="width:150px">
          <el-option label="常规" value='10'></el-option>
          <el-option label="冷链" value='40'></el-option>
          <el-option label="鲜食" value='42'></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动状态">
        <el-select v-model="searchInfo.check_status" @change="pageChange" clearable style="width:150px">
          <el-option label="草稿" value="1"></el-option>
          <el-option label="待审核" value="2"></el-option>
          <el-option label="审核中" value="3"></el-option>
          <el-option label="审核不通过" value="4"></el-option>
          <el-option label="未开始" value="5"></el-option>
          <el-option label="进行中" value="6"></el-option>
          <el-option label="已结束" value="7"></el-option>
          <el-option label="已作废" value="99"></el-option>
        </el-select>
      </el-form-item>
      </div>
      <el-form-item label="套餐名称">
        <el-input v-model="searchInfo.promotion_name" placeholder="套餐名称" style="width:150px"></el-input>
      </el-form-item>
      <el-form-item label="套餐ID">
        <el-input v-model="searchInfo.promotion_id" placeholder="套餐ID" style="width:150px"></el-input>
      </el-form-item>
      <el-form-item label="ERP套餐ID" label-width="100px">
        <el-input v-model="searchInfo.packageId" placeholder="ERP套餐ID"></el-input>
      </el-form-item>
      <el-form-item label="活动起止时间" label-width="100px">
        <el-date-picker v-model="startStopTime" type="daterange" value-format="yyyy-MM-dd" @change="daterangeFormat" style="width:220px" placeholder="活动起止时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  @click="searchList">查询</el-button>
        <el-button type="primary" @click="checkColumn = true">导出</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableList" border v-loading="tableLoading">
      <el-table-column label="ID" prop="id" align="center"></el-table-column>
      <el-table-column label="分公司" prop="branchName" align="center" width="130"></el-table-column>
      <el-table-column label="所属部门" prop="departName" align="center"></el-table-column>
      <el-table-column label="所属设备" align="center">
        <template scope="scope">
          <span v-if="scope.row.client === 0">全部</span>
          <span v-if="scope.row.client === 10">PC订货</span>
          <span v-if="scope.row.client === 20">惠配通</span>
          <span v-if="scope.row.client === 30">惠付通</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center">
        <template scope="scope">
          <span v-if="scope.row.limit_store_id === '0'">全部</span>
          <span v-if="scope.row.limit_store_id !== '0'">{{scope.row.limitStoreName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="客资类型" prop="customerName" align="center"></el-table-column>
      <el-table-column label="套餐ID"  width="130" prop="promotion_id" align="center"></el-table-column>
      <el-table-column label="ERP套餐ID" width="130" prop="packageId" align="center"></el-table-column>
      <el-table-column label="套餐名称" prop="promotion_name" align="center"></el-table-column>
      <el-table-column label="商品类型" prop="product_type" align="center">
        <template scope="scope">
          <span v-if="scope.row.product_type === 10">常规</span>
          <span v-if="scope.row.product_type === 40">冷链</span>
          <span v-if="scope.row.product_type === 42">鲜食</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐原价" prop="price_total" align="center"></el-table-column>
      <el-table-column label="套餐成本价" prop="cgprice" align="center"></el-table-column>
      <el-table-column label="套餐原毛利" prop="oldml" align="center"></el-table-column>
      <el-table-column label="套餐促销价" prop="price_real_total" align="center"></el-table-column>
      <el-table-column label="套餐促销毛利率" align="center">
        <template scope="scope">{{scope.row.cxmll}}%</template>
      </el-table-column>
      <el-table-column label="套餐促销毛利" prop="cxml" align="center"></el-table-column>
      <el-table-column label="套餐促销毛利损失" prop="cxmlss" align="center"></el-table-column>
      <el-table-column label="开始时间" prop="start_time" align="center" width="180"></el-table-column>
      <el-table-column label="结束时间" prop="end_time" align="center" width="180"></el-table-column>
      <el-table-column label="申请人" prop="updateUser" align="center"></el-table-column>
      <el-table-column label="申请时间" prop="updateTime" align="center" width="180"></el-table-column>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip align="center"></el-table-column>
      <el-table-column label="活动状态" prop="status" align="center"></el-table-column>
      <el-table-column label="操作" align="center" min-width="180" fixed="right">
        <template scope="scope">
          <el-button v-if="scope.row.status === '草稿' || scope.row.status === '审核不通过'" @click="handle(scope.$index, scope.row, $event)" size="small">编辑</el-button>
          <el-button v-if="scope.row.status === '待审核' || scope.row.status === '审核中' || scope.row.status === '审核不通过' || scope.row.status === '未开始' || scope.row.status === '进行中'
          || scope.row.status === '已结束' || scope.row.status === '已作废'" @click="handle(scope.$index, scope.row, $event)" size="small">详情</el-button>
          <el-button v-if="scope.row.status === '草稿' || scope.row.status === '审核不通过' || scope.row.status === '下线'" @click="handle(scope.$index, scope.row, $event)" size="small">删除</el-button>
          <el-button v-if="scope.row.status === '待审核'" @click="handle(scope.$index, scope.row, $event)" size="small">撤回</el-button>
          <el-button v-if="scope.row.status === '未开始' || scope.row.status === '进行中'" @click="handle(scope.$index, scope.row, $event)" size="small">作废</el-button>
          <el-button v-if="scope.row.status === '待审核' || scope.row.status === '审核中' || scope.row.status === '审核不通过' || scope.row.status === '审核不通过'
          || scope.row.status === '未开始' || scope.row.status === '进行中' || scope.row.status === '已结束' || scope.row.status === '已作废'" @click="handle(scope.$index, scope.row, $event)" size="small">复制</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :page-size="Number(searchInfo.pageSize)"
      layout="total, prev, pager, next"
      :total="Number(searchInfo.total)"
      style="padding-top:10px;text-align: right;">
    </el-pagination>
    <el-dialog title="排序" :visible.sync="setSortDialog">
      <el-form :inline="true">
        <el-form-item label="分公司">
          <el-input v-model="this.branchName" disabled="disabled" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="客资类型">
          <el-select v-model="sortInfo.limit_user_type" placeholder="客资类型" style="width:150px" :loading="customerTypeLoading">
            <!-- <el-option value="1" label="普通超市"></el-option> -->
            <el-option v-for="(item, index) in customerTypeList"
            :key="index"
            :label="item.name"
            :value="item.id.toString()"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="searchSortList">查询</el-button>
        <el-button type="primary" @click="sortSubmit">提交</el-button>
      </el-form>
      <el-table :data="setSortTableList" border v-loading="setTableLoading">
        <!--<el-table-column label="序号" prop="sort_value" align="center"></el-table-column>-->
        <el-table-column label="序号" align="center">
          <template scope="scope">
            <el-input style="width: 100px" v-model="scope.row.sort_value"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="套餐ID" prop="id" align="center"></el-table-column>
        <el-table-column label="套餐名称" prop="promotion_name" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template scope="scope" align="center">
            <el-button size="small" v-if="scope.row.sort_value === 0 || scope.$index !== 0"
            @click="handleSetSort('置顶', scope.$index)">置顶</el-button>
            <el-button size="small" v-if="scope.row.sort_value !== 0 && scope.$index !== 0"
            @click="handleSetSort('上移', scope.$index)">上移</el-button>
            <el-button size="small" v-if="scope.row.sort_value !== 0 && scope.$index !== setSortTableList.length - 1"
            @click="handleSetSort('下移', scope.$index)">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="导出字段筛选" size="small" :visible.sync="checkColumn">
      <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
      <div style="margin: 15px 0;"></div>
      <el-checkbox-group v-model="checkedOptions" @change="handleCheckedCitiesChange">
        <el-checkbox
          v-for="item in Options"
          :label="item.name">
          {{item.text}}
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportFile">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { apiHost, apiURL } from '../../../../../config/settings.js'
  import { getInfo, activity } from '../../../../../config/proxy.js'
  import mixins from '../../../../../components/mixins.vue'
  export default {
    mixins: [mixins],
    data () {
      return {
        checkAll: false,
        isIndeterminate: true,
        checkedOptions: [],   // 选中的
        Options: [],          // 选项集合
        checkColumn: false,   // 导出字段筛选弹窗
        checkedShow: [],      // 全选展示
        searchInfo: {
          limit_branch_id: '', // 分公司id
          limit_department: '', // 部门名称
          limit_user_type: '', // 客资类型
          promotion_name: '', // 套餐名称
          promotion_id: '', // 套餐ID
          start_time: '', // 开始时间
          end_time: '', // 结束时间
          packageId: '', // erp套餐id
          product_type: '', // 商品类型
          promotion_type: 1,
          check_status: '', // 活动状态
          page: 1,
          pageSize: 10,
          total: 0,
          sortType: 2, // 排序类型 1 排序值 2 创建时间
          orderBy: 2
        },
        startStopTime: '', // 活动起止时间
        tableList: [], // table列表
        tableLoading: false, // table loading
        setTableLoading: false, // setTable 加载loading
        customerTypeList: [], // 客资类型
        customerTypeLoading: true, // 客资类型加载
        setSortDialog: false, // 排序提示框
        setSortTableList: [], // 排序数组
        sortInfo: {
          limit_branch_id: '',
          limit_department: '',
          limit_user_type: '',
          promotion_type: 1,
          page: 1,
          pageSize: 200,
          check_status: 6, // 活动状态
          orderBy: 2,
          short_select: 1 //
        }
      }
    },
    methods: {
      handleCheckAllChange (val) {
        this.checkedOptions = val ? this.checkedShow : []
        this.isIndeterminate = false
      }, // 全选
      handleCheckedCitiesChange (value) {
        let checkedCount = value.length
        this.checkAll = checkedCount === this.Options.length
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.Options.length
      }, // 单选
      exportFile () { // 导出
        if (this.checkedOptions.length === 0) {
          this.message('请勾选要导出的项', 'error')
          return false
        }
        this.searchInfo.reqColumnName = this.checkedOptions
        var _data = this.searchInfo
        var form = document.createElement('form')
        document.body.appendChild(form)
        form.method = 'post'
        form.action = 'http://' + apiHost.newCms + ':20000' + apiURL.sphd_export
        // console.log(params.length)
        for (var i in _data) {
          var newInput = document.createElement('input')
          newInput.setAttribute('name', i)
          newInput.setAttribute('type', 'hidden')
          newInput.setAttribute('value', _data[i])
          form.appendChild(newInput)
        }
        form.submit()
        form.remove()
      }, // 导出
      pageChange () {
        this.searchInfo.page = 1
      },
      sortSubmit () {
        const newArr = []
        this.setSortTableList.forEach((item, index) => {
          const newItem = {}
          newItem.promotion_id = item.promotion_id
          newItem.sort_value = Number(item.sort_value)
          newArr.push(newItem)
        })
        var _data = {
          sortRequest: newArr
        }
        activity.sphd.setSort(_data, (res) => {
          if (res.message === 'ok') {
            this.searchSortList()
            this.message('设置排序成功', 'success')
          } else {
            this.message('设置排序失败', 'error')
          }
        })
      }, // 排序提交
      templateAdd () { // 新增普通套餐
        this.openNewWindow('pttc_add', '新增普通套餐', 'pttc_add')
      },
      searchCustomerType () { // 查询客资类型
        var _data = ''
        getInfo.client(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.customerTypeList = res.content.content
            this.customerTypeLoading = false
          }
        })
      },
      searchList () { // 查询列表
        var _data = this.searchInfo
        _data.sortType = 2
        this.tableLoading = true
        console.log(_data)
        activity.sphd.list(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.tableLoading = false
            this.tableList = res.content.list
            this.searchInfo.total = res.content.count
            // this.searchInfo.page = res.content.page
            // console.log(this.tableData)
            this.fenToYuan()
            this.matchState(this.tableList)
          } else {
            this.tableLoading = false
            this.message('查询失败', 'error')
          }
        })
      },
      fenToYuan () {
        if (this.tableList) {
          for (let index = 0; index < this.tableList.length; index++) {
            const element = this.tableList[index]
            element.price_total = (element.price_total / 100).toFixed(2)
            element.cgprice = (element.cgprice / 100).toFixed(2)
            element.oldml = (element.oldml / 100).toFixed(2)
            element.price_real_total = (element.price_real_total / 100).toFixed(2)
            element.cxmll = element.cxmll
            element.cxml = (element.cxml / 100).toFixed(2)
            element.cxmlss = (element.cxmlss / 100).toFixed(2)
          }
        }
      },
      searchSortList () {
        var _data = this.sortInfo
        _data.sortType = 1
        if (this.sortInfo.limit_user_type === '') {
          this.message('请选择客资类型', 'error')
        } else {
          this.setTableLoading = true
          console.log(_data)
          activity.sphd.list(_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.setTableLoading = false
              this.setSortTableList = res.content.list
              // this.searchInfo.total = res.content.count
              // this.searchInfo.page = res.content.page
              this.matchState(this.tableList)
              // console.log(this.tableData)
            } else {
              this.setTableLoading = false
              this.message('查询失败', 'error')
            }
          })
        }
      },
      matchState (res) { // 匹配状态
        if (res) {
          for (var i = 0; i < res.length; i++) {
            if (res[i].status === 1) { res[i].status = '草稿' }
            if (res[i].status === 2) { res[i].status = '待审核' }
            if (res[i].status === 3) { res[i].status = '审核中' }
            if (res[i].status === 4) { res[i].status = '审核不通过' }
            if (res[i].status === 5) { res[i].status = '未开始' }
            if (res[i].status === 6) { res[i].status = '进行中' }
            if (res[i].status === 7) { res[i].status = '已结束' }
            if (res[i].status === 99) { res[i].status = '已作废' }
          }
        }
      },
      handleClickSetSort () {
        this.setSortDialog = true
        console.log(this.searchInfo)
      },
      handleSetSort (text, index) { // 排序
        // this.setSortDialog = true
        // console.log()
        switch (text) {
          case '置顶':
            // this.setSortTableList[index] = this.setSortTableList.splice(0, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            var bestArr = []
            for (let index = 0; index < this.setSortTableList.length; index++) {
              const element = this.setSortTableList[index]
              bestArr.push(element.sort_value)
            }
            console.log(bestArr)
            bestArr.sort(this.sortNumber)
            console.log(bestArr)
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, bestArr[bestArr.length - 1] + 1)
            break
          case '上移':
            // this.setSortTableList[index] = this.setSortTableList.splice(index - 1, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, this.setSortTableList[index - 1].sort_value)
            this.handlClickeSetSort(this.setSortTableList[index - 1].promotion_id, this.setSortTableList[index].sort_value)
            break
          default:
            this.handlClickeSetSort(this.setSortTableList[index].promotion_id, this.setSortTableList[index + 1].sort_value)
            this.handlClickeSetSort(this.setSortTableList[index + 1].promotion_id, this.setSortTableList[index].sort_value)
            // this.setSortTableList[index] = this.setSortTableList.splice(index + 1, 1, this.setSortTableList[index])[0]
            // console.log(this.setSortTableList[index])
            break
        }
      },
      sortNumber (a, b) {
        return a - b
      },
      handlClickeSetSort (id, val) { // 设置排序方法
        var _data = {
          promotionId: id,
          // productId: '',
          sortValue: val
        }
        console.log(_data)
        activity.sphd.setSort(_data, (res) => {
          console.log(res)
          if (res.message === 'ok') {
            this.searchSortList()
            this.message('设置排序成功', 'success')
          } else {
            this.message('设置排序失败', 'error')
          }
        })
      },
      handle (index, row, event) { // 操作
        // console.log(event)
        const handleName = event.target.innerText
        console.log(handleName)
        switch (handleName) {
          case '详情':
            this.openNewWindow('pttc_detail', '普通套餐详情', 'pttc_detail', row.id)
            // this.fullDetail = true
            // activity.yhqhd.dddd.detail({id: row.id}, (res) => {
            //   console.log(res)
            //   if (res.message === 'ok') {
            //     this.detailData = res.content
            //     this.detailDialog = true
            //     // if (res.content.products.length !== 0) {
            //     //   this.productsDetail = true
            //     // } else {
            //     //   this.productsDetail = false
            //     // }
            //   } else {
            //     this.message('查看详情', 'error')
            //   }
            // })
            break
          case '编辑':
            this.openNewWindow('pttc_bj', '编辑普通套餐', 'pttc_add', row.id)
            break
          case '复制':
            this.openNewWindow('pttc_fz', '复制普通套餐', 'pttc_add', row.id)
            break
            // 状态值 1,草稿 2,待审核 3,审核中 ,4 审核不通过 5,审核通过 100 删除 99,已作废
          case '删除':
            this.buttonPublicMethods('删除', '100', row)
            break
          case '撤回':
            this.buttonPublicMethods('撤回', '1', row)
            break
          case '作废':
            this.buttonPublicMethods('作废', '99', row)
            break
          default:
            break
        }
      },
      buttonPublicMethods (text, status, row) { // 删除 撤回 作废 发券公共方法
        this.$confirm('您确定要' + text + '吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var _data = {
            id: row.id,
            status: status,
            userId: this.userId,
            userName: this.userName,
            promotionType: '1'
          }
          activity.sphd.handle(_data, (res) => {
            console.log(res)
            if (res.message === 'ok') {
              this.searchList()
              this.message(text + '成功', 'success')
            } else {
              this.message(text + '失败', 'error')
            }
          })
        }).catch(() => {
        })
      },
      handleCurrentChange (val) { // 分页
        this.searchInfo.page = val
        this.tableData = []
        this.isLoading = true
        this.searchList()
      },
      // openNewWindow (menuId, menuName, perController, uid) { // 新增tab方法
      //   var _data = {
      //     menu_id: menuId,
      //     menu_name: menuName,
      //     per_controller: perController
      //   }
      //   console.log(this.listData, 'listData')
      //   this.listData.forEach(element => {
      //     console.log(menuId.split('_')[0], element.component)
      //     if (menuId.split('_')[0] === element.component) {
      //       console.log(element.selMenu)
      //       _data.selMenu = element.selMenu
      //     }
      //   })
      //   if (uid) {
      //     _data.uid = uid
      //   }
      //   this.$store.dispatch('addTab', _data)
      // },
      daterangeFormat (t) { // 时间段格式化
        if (t) {
          this.searchInfo.start_time = t[0]
          this.searchInfo.end_time = t[1]
        } else {
          this.searchInfo.start_time = ''
          this.searchInfo.end_time = ''
        }
      },
      message (text, type) { // 消息提示
        this.$message({
          showClose: true,
          message: text,
          type: type
        })
      }
    },
    computed: {
      listData: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.tab.listData
      },
      update_state: function () {
        // console.log(state.updateState.dhmState)
        return this.$store.state.updateState.pttcState
      },
      userName: function () {
        if (!this.$store.state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return this.$store.state.user.info.user_name
      },
      userId: function () {
        return this.$store.state.user.info.user_id
      },
      roleId: function () {
        return this.$store.state.user.info.roleid
      },
      branchName: function () {
        return this.$store.state.user.info.branchId === 1 ? '总公司' : this.$store.state.user.info.branchName
      },
      branchId: function () {
        return this.$store.state.user.info.branchId
      },
      deptName: function () {
        return this.$store.state.user.info.parOrgName
      },
      deptId: function () {
        return this.$store.state.user.info.or_org_id
      },
      branchOrgId: function () {
        return this.$store.state.user.info.branchOrgId
      },
      uorId: function () {
        return this.$store.state.user.info.uor_id
      }
    },
    created () {
      getInfo.getColumns({promotion_type: 1}, res => {
        this.Options = res.content
        this.Options.forEach(item => {
          this.checkedShow.push(item.name)
        })
      })
      this.searchCustomerType()
      this.searchInfo.limit_branch_id = this.branchId // 分公司id
      // this.searchInfo.limit_department = this.deptId // 部门id
      this.sortInfo.limit_branch_id = this.branchId // 分公司id
      // this.sortInfo.limit_department = this.deptId // 部门id
    },
    watch: {
      update_state (curVal, oldVal) {  // 监听 更新状态 查询list
        this.searchList()
      }
    }
  }
</script>
